package com.atguigu.crowd.handler;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.vo.AddressVO;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.entity.vo.OrderProjectVO;
import com.atguigu.crowd.util.ResultEntity;

@Controller
public class OrderHandler {

	@Autowired
	private MySQLRemoteService mySQLRemoteService;

    private Logger logger=LoggerFactory.getLogger(OrderHandler.class);
	
	@RequestMapping("/confirm/return/info/{returnId}")
	public String showReturnConfirmInfo(@PathVariable("returnId") Integer returnId, HttpSession session) {
		ResultEntity<OrderProjectVO> resultEntity = mySQLRemoteService.getOrderProjectVORemote(returnId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			OrderProjectVO orderProjectVO = resultEntity.getData();
			session.setAttribute("orderProjectVO", orderProjectVO);
		}
		return "confirm_return";
	}

	@RequestMapping("/confirm/order/{returnCount}")
	public String showConfirmOrderInfo(@PathVariable("returnCount") Integer returnCount, HttpSession session) {
		// 1.把接收到的回报数量合并到 Session 域
		OrderProjectVO orderProjectVO = (OrderProjectVO) session.getAttribute("orderProjectVO");
		orderProjectVO.setReturnCount(returnCount);
		session.setAttribute("orderProjectVO", orderProjectVO);
		// 2.获取当前已登录用户的 id
		MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		Integer memberId = memberLoginVO.getId();
		// 3.查询目前的收货地址数据
		ResultEntity<List<AddressVO>> resultEntity = mySQLRemoteService.getAddressVORemote(memberId);
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<AddressVO> list = resultEntity.getData();
			session.setAttribute("addressVOList", list);
		}
		return "confirm_order";
	}
	
    @RequestMapping("/save/address")
    public String saveAddress(AddressVO addressVO,HttpSession session){
//        执行地址保存
        ResultEntity<String> resultEntity=mySQLRemoteService.saveAddressRemote(addressVO);
        logger.debug("地址保存处理结果"+resultEntity.getResult());
        OrderProjectVO orderProjectVO = (OrderProjectVO) session.getAttribute("orderProjectVO");

        Integer returnCount = orderProjectVO.getReturnCount();

        return "redirect:http://127.0.0.1/order/confirm/order/"+returnCount;
    }

}
